import { getUserInfo } from '@/apis/user';
import Bg from '@/assets/choise-bg.jpg';
import StartButton from '@/assets/drive-100.png';
import BusNike from '@/components/Bus/Nike';
import Compressor from 'compressorjs';
import TweenOne from 'rc-tween-one';
import { history, useMutation, useQuery } from 'umi';

import ButtonConfirm from '@/assets/button-confirm.png';
import ButtonReUpload from '@/assets/button-reupload.png';

import SubTitle from '@/assets/drive-98.png';
import Title from '@/assets/drive-99.png';

import { UploadManhuaAvatar } from '@/apis';
import { BUS_THEME, Bus, BusHead, StartBus } from '@/apis/bus';
import BusZhuDi from '@/components/Bus/Zhudi';
import '@animxyz/core';
import { XyzTransitionGroup } from '@animxyz/react';
import { Toast } from 'react-vant';

export default function Page() {
  const theme = parseInt(
    sessionStorage.getItem('theme') || `${BUS_THEME.NIKE}`,
  ) as BUS_THEME;

  const { data: user } = useQuery(['get:user'], getUserInfo);

  // ?确认发车
  const { mutateAsync: mutateStartBusAsync } = useMutation(StartBus);

  // ?获取我的发车记录
  const { data: bus, refetch: refetchBus } = useQuery(['bus:detail'], () =>
    Bus(),
  );

  // ?上传头像
  const { data: avatarRes, mutateAsync: mutateAvatarAsync } = useMutation(
    UploadManhuaAvatar,
    {
      onSuccess: function (data) {},
    },
  );

  // ?更新头像
  const { mutateAsync: mutateBusHeadAsync } = useMutation(BusHead, {
    onSuccess: function () {
      refetchBus();
    },
  });

  async function handleUpload(file: Blob | File) {
    Toast.loading({ message: '上传中', duration: 0 });
    new Compressor(file, {
      quality: 0.6,
      maxWidth: 1000,
      async success(result) {
        await mutateAvatarAsync(result);
        Toast.clear();
      },
      error(err) {
        console.log(err.message);
      },
    });
  }

  function handleTrickUploadClick() {
    const upload = document.querySelector(
      '.participants-upload-input-1',
    ) as HTMLElement;
    if (!upload) return;
    upload.click();
  }

  return (
    <>
      <XyzTransitionGroup
        appear
        appearVisible
        xyz="fade up-2 appear-stagger"
        className="bg-cover bg-no-repeat bg-center min-h-screen relative overflow-hidden pt-[150px]"
        style={{
          backgroundImage: `url(${Bg})`,
        }}
      >
        <h1
          className="w-[486px] h-[82px] bg-cover mx-auto"
          style={{
            backgroundImage: `url(${Title})`,
          }}
        ></h1>
        <h6
          className="w-[488px] h-[108px] mx-auto bg-cover mt-4"
          style={{
            backgroundImage: `url(${SubTitle})`,
          }}
        ></h6>

        {/* bus */}
        <div className=" relative mt-12" xyz="fade">
          <TweenOne
            animation={{
              type: 'from',
              x: window.innerWidth + 500,
              duration: 3000,
            }}
            className="busContainer w-[1560px] relative -left-[410px] top-0"
          >
            {theme === BUS_THEME.NIKE && (
              <BusNike
                readonlyFriend={Boolean(avatarRes?.img)}
                selfAvatar={avatarRes?.img}
                onUploadSelfAvatar={(e) => {
                  const file = e.target.files?.[0];
                  if (!file) return;
                  handleUpload(file);
                }}
                onUploadFriendAvatar={(e) => {
                  const file = e.target.files?.[0];
                  if (!file) return;
                  handleUpload(file);
                }}
              />
            )}
            {theme === BUS_THEME.ZHUDI && (
              <BusZhuDi
                readonlyFriend={Boolean(avatarRes?.img)}
                selfAvatar={avatarRes?.img}
                onUploadSelfAvatar={(e) => {
                  const file = e.target.files?.[0];
                  if (!file) return;
                  handleUpload(file);
                }}
                onUploadFriendAvatar={(e) => {
                  const file = e.target.files?.[0];
                  if (!file) return;
                  handleUpload(file);
                }}
              />
            )}
          </TweenOne>
        </div>

        {/* start button */}
        {!avatarRes?.img && (
          <button
            onClick={() => {
              handleTrickUploadClick();
            }}
            className="w-[560px] h-[106px] bg-cover  active:scale-95 mt-10 mx-auto block"
            style={{
              backgroundImage: `url(${StartButton})`,
              backgroundSize: '100% 100%',
            }}
          ></button>
        )}

        {avatarRes?.img && (
          <button
            onClick={async () => {
              if (!theme) return Toast('没有选择主题');

              const t = Toast.loading({ duration: 0 });

              // #step1 开始发车
              const res = await mutateStartBusAsync({ theme });
              if (!res.id) return Toast('发车失败， 请重试');

              // #step2 关联头像
              await mutateBusHeadAsync({ busId: res.id, head: avatarRes?.img });
              t.clear();

              history.replace(`/render?busId=${res?.id}`);
            }}
            className="w-[472px] h-[90px] mx-auto block bg-cover active:scale-95 mb-2 mt-10"
            style={{
              backgroundImage: `url(${ButtonConfirm})`,
            }}
          />
        )}

        {avatarRes?.img && (
          <button
            onClick={() => {
              handleTrickUploadClick();
            }}
            className="w-[472px] h-[90px] mx-auto block bg-cover active:scale-95"
            style={{
              backgroundImage: `url(${ButtonReUpload})`,
            }}
          />
        )}
      </XyzTransitionGroup>
    </>
  );
}
